package com.appleyk.config;

import com.appleyk.utils.CustomDictWordUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.CommandLineRunner;
import org.springframework.core.io.ClassPathResource;
import org.springframework.stereotype.Component;
import sun.applet.Main;

import java.io.*;
import java.net.URL;

/**
 * <p>全局配启动 -- 初始化项目时，执行命令，将相关额外的自定义词典加载下</p>
 *
 * @author
 */
@Component
@Slf4j
public class ConfigRunner implements CommandLineRunner {

    private static final String nameDictPath = "statics/data/custom/nameDict.txt";
    private static final String departmentsDictPath = "statics/data/custom/departmentsDict.txt";

    @Value("${HanLP.CustomDictionary.cache.path}")
    private String cacheDictPath;

    @Override
    public void run(String... args){
        //先删除缓存
        File file = new File(cacheDictPath);
        if(file.exists()){
            if(!file.delete()){
                log.error("delete CustomDictionary.txt.bin fail, Please manually delete！");
            }
            System.out.println("CustomDictionary.txt.bin delete success .");
        }
        // 添加自定义员工姓名词典
        loadDict(nameDictPath,0);
        // 添加自定义部门词典
        loadDict(departmentsDictPath,1);
    }

    /**
     * 加载自定义词性字典
     * @param path 字典路径
     * @param type 类型
     */
    public void loadDict(String path,Integer type) {
        // 使用getResourceAsStream方法获取资源的输入流
        ClassLoader classLoader = getClass().getClassLoader();
        URL resourceUrl = classLoader.getResource(path);
        BufferedReader br;
        try {
            if(resourceUrl  != null){
                br = new BufferedReader(new InputStreamReader(resourceUrl.openStream()));
                addCustomDictionary(br, type);
            }
        }catch (Exception e) {
            log.error("加载自定义词性字典失败", e);
        }
    }


    /**
     * 添加自定义分词及其词性，注意数字0表示频率，不能没有
     *
     * @param br 字节流（读）
     * @param type 字典类型
     */
    public void addCustomDictionary(BufferedReader br, int type) {
        String word;
        try {
            while ((word = br.readLine()) != null) {
                switch (type) {
                    case 0: // 人名 nnt
                        CustomDictWordUtils.setNatureAndFrequency(word,"nr 0",true);
                        break;
                    case 1: // 部门名称 nmd
                        CustomDictWordUtils.setNatureAndFrequency(word,"nmd 0",true);
                        break;
                    /**设置电影评分数词 词性 == x 0*/
                    case 2:
                        CustomDictWordUtils.setNatureAndFrequency(word,"x 0",true);
                        break;
                    default:
                        break;
                }
            }
            br.close();
        } catch (NumberFormatException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
